
import React, { PureComponent } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { Form, Input, Button, Radio, Switch, Row, Col } from 'antd'
import InputNumberWithSuffix from "@common/presentational/InputNumberWithSuffix";
import PageBackHeader from '@common/PageBackHeader'
import ImageUpload from '@common/presentational/ImageUpload'
import { getHistoryMatchParams } from '@utils/setUrlQuery'
import { priceFenToYuan, priceYuanToFen } from '@utils/priceConversion'
import { DEFAULT_COVER } from '@constants/CustomerMember'
import {
    createCustomerMember,
    editCustomerMember,
} from '@sagas/customer'

const FormItem = Form.Item
const initialValue = {
    name: '',
    card_type: 'normal',
    cover: DEFAULT_COVER,
    cover_type: 'default',
    can_integral: false,
    unit_integral_amount: '',
    can_recharge: false,
    topup_limit: '',
}
const getReformedData = (data) => {
    const _data = {
        ...data
    }
    _data.cover_type = _data.cover === DEFAULT_COVER ? 'default' : 'custom'
    _data.unit_integral_amount = _data.unit_integral_amount ? priceFenToYuan(_data.unit_integral_amount) : _data.unit_integral_amount
    _data.topup_limit = _data.topup_limit ? priceFenToYuan(_data.topup_limit) : _data.topup_limit
    return {
        ..._data,
    }
}
const getSaveFormedData = (data) => {
    const _data = {
        ...data
    }
    _data.unit_integral_amount = _data.unit_integral_amount ? priceYuanToFen(_data.unit_integral_amount) : _data.unit_integral_amount
    _data.topup_limit = _data.topup_limit ? priceYuanToFen(_data.topup_limit) : _data.topup_limit
    delete _data.cover_type
    return {
        ..._data,
    }
}

@withRouter
@connect(() => ({
}), {
    createCustomerMember,
    editCustomerMember,
})

class CustomerMemberCreatePage extends PureComponent {
    constructor(props) {
        super(props)
        const { location } = props
        const { id } = getHistoryMatchParams(props)
        const { state = {} } = location
        this.state = {
            id,
            DEFAULT_COVER,
            formData: id ? {
                ...initialValue,
                ...getReformedData(state)
            } : {
                ...initialValue,
            },
        }

        this.formRef = React.createRef()

        this.handleCoverChange = this.handleCoverChange.bind(this)
        this.handleCoverTypeChange = this.handleCoverTypeChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
        this.handleSave = this.handleSave.bind(this)
        this.handleCancel = this.handleCancel.bind(this)
    }

    handleCoverChange(value) {
        const { formData } = this.state
        this.setState({
            formData: {
                ...formData,
                cover: value,
            },
        })
    }

    handleCoverTypeChange(e) {
        const { formData } = this.state
        const value = e.target.value
        let cover = ''
        if (value === 'default') {
            cover = DEFAULT_COVER
        } else if (value === 'custom') {
            cover = ''
        }
        this.setState({
            formData: {
                ...formData,
                cover,
            },
        })
    }

    handleSubmit(values) {
        const { id: card_id, formData } = this.state
        const { createCustomerMember, editCustomerMember } = this.props
        const _data = getSaveFormedData({
            ...formData,
            ...values,
        });
        card_id ? editCustomerMember({
            card_id,
            ..._data,
        }, () => {
            this.handleCancel()
        }) : createCustomerMember({
            ..._data,
        }, () => {
            this.handleCancel()
        })
    }

    handleSave() {
        this.formRef.current?.submit()
    }

    handleCancel() {
        this.props.goBack ? this.props.goBack() : this.props.history.goBack()
    }

    render() {
        const { id, formData } = this.state
        return (
            <div className="bilin-web customer-member-create-page">
                <PageBackHeader title={id ? '编辑会员卡' : '新建会员卡'} />
                <div className="bilin-web-body form-page with-footer">
                    <Form
                        ref={this.formRef}
                        name="coupon-form"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        initialValues={formData}
                        scrollToFirstError={{
                            behavior: actions =>
                                actions.forEach(({ el, top, left }) => {
                                    el.scrollTop = top - 100
                                    el.scrollLeft = left
                                }),
                        }}
                        onFinish={this.handleSubmit}
                    >
                        <div className="ft-16 pdb-36">基本信息</div>
                        <FormItem
                            label="会员名称"
                            name="name"
                            rules={[
                                { required: true, message: '请输入会员名称', },
                            ]}
                        >
                            <Input placeholder="请输入会员名称" maxLength={8} />
                        </FormItem>
                        <FormItem
                            label="封面背景"
                            name="cover_type"
                            rules={[
                                { required: true, message: '请选择封面背景', },
                            ]}
                        >
                            <Radio.Group onChange={this.handleCoverTypeChange}>
                                <Radio value='default'>默认</Radio>
                                <Radio value='custom'>自定义</Radio>
                            </Radio.Group>
                        </FormItem>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.cover_type !== currentValues.cover_type}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('cover_type') === 'custom' ? (<>
                                    <ImageUpload
                                        className="cover-upload-container"
                                        value={formData.cover}
                                        maxFileSize="6M"
                                        aspectRatio={686 / 274}
                                        accept="image/png, image/jpeg, image/jpg"
                                        uploadIntro={(
                                            <div className="ft-clr-ml mgl-32" style={{width: '150px'}}>
                                                <p>尺寸：686 x 274PX</p>
                                                <p>格式：jpg、jpeg、png</p>
                                                <p>大小：不超过6M</p>
                                            </div>
                                        )}
                                        onChange={this.handleCoverChange}
                                    />
                                </>
                                ) : null
                            }}
                        </Form.Item>
                        <div className="ft-16 pdt-16 pdb-36">会员权益</div>
                        <Form.Item
                            noStyle
                        >
                            <Row className='flex-vertical-center'>
                                <Col span={4}>充值权益</Col>
                                <Col span={2}>
                                    <Form.Item
                                        noStyle
                                        name="can_recharge"
                                        valuePropName="checked"
                                    >
                                        <Switch />
                                    </Form.Item>
                                </Col>
                                <Col span={8}><span className="mgl-16 ft-clr-ml">开启后，该卡支持会员储值消费</span></Col>
                            </Row>
                        </Form.Item>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.can_recharge !== currentValues.can_recharge}
                        >
                            {({getFieldValue}) => {
                                return getFieldValue('can_recharge') ? (<Row className='flex-vertical-center'>
                                    <Col span={4} />
                                    <Col span={2}>
                                        <span>最低起充</span>
                                    </Col>
                                    <Col span={8}>
                                        <FormItem
                                            noStyle
                                            name='topup_limit'
                                            rules={[
                                                { required: true, message: '请输入最低起充金额', },
                                            ]}
                                        >
                                            <InputNumberWithSuffix 
                                                min={0.01}
                                                max={100000}
                                                step={1}
                                                precision={2}
                                                placeholder="请输入最低起充金额" 
                                                style={{ width: '280px' }}
                                                suffix={(
                                                    <span>元</span>
                                                )}
                                            />
                                        </FormItem>
                                    </Col>
                                </Row>) : null
                            }}
                        </Form.Item>
                        <Form.Item
                            noStyle
                        >
                            <Row className='flex-vertical-center'>
                                <Col span={4}>积分权益</Col>
                                <Col span={2}>
                                    <Form.Item
                                        noStyle
                                        name="can_integral"
                                        valuePropName="checked"
                                    >
                                        <Switch />
                                    </Form.Item>
                                </Col>
                                <Col span={8}><span className="mgl-16 ft-clr-ml">开启后，该持卡会员消费可获积分</span></Col>
                            </Row>
                        </Form.Item>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.can_integral !== currentValues.can_integral}
                        >
                            {({getFieldValue}) => {
                                return getFieldValue('can_integral') ? (<Row className='flex-vertical-center'>
                                    <Col span={4} />
                                    <Col span={2}>
                                        <span>每消费</span>
                                    </Col>
                                    <Col span={8}>
                                        <FormItem
                                            noStyle
                                            name='unit_integral_amount'
                                            rules={[
                                                { required: true, message: '请输入消费金额', },
                                            ]}
                                        >
                                            <InputNumberWithSuffix 
                                                min={0.01}
                                                max={100000}
                                                step={1}
                                                precision={2}
                                                placeholder="请输入消费金额" 
                                                style={{ width: '280px' }}
                                                suffix={(
                                                    <span>元，积1分</span>
                                                )}
                                            />
                                        </FormItem>
                                    </Col>
                                </Row>) : null
                            }}
                        </Form.Item>
                    </Form>
                </div>
                <div className="bilin-web-footer">
                    <Button type="primary" ghost onClick={this.handleCancel}>取消</Button>
                    <Button type="primary" onClick={this.handleSave}>保存</Button>
                </div>
            </div>
        )
    }
}

export default CustomerMemberCreatePage